<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/layui/layui.js"></script>
    <script src="${pageContext.request.contextPath}/layui/jquery-1.10.2.min.js"></script>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layui/css/layui.css"/>
</head>
<body>
<table id="demo" lay-filter="test"></table>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script>
    layui.use('table', function () {
        var table = layui.table;

        //第一个实例
        table.render({
            elem: '#demo'
            , height: 500
            , toolbar: true
            , url: '${pageContext.request.contextPath}/users' //数据接口
            , page: {
                limit: 3,//每页限定
                limits: [3, 5, 8],
                first: '首页',
                last: '尾页'
            } //开启分页
            , cols: [[ //表头
                {field: 'id', title: '编号', sort: true, fixed: 'left'}
                , {field: 'name', title: '用户名'}
                , {field: 'password', title: '密码'}
                , {field: 'sex', title: '性别', sort: true}
                , {field: 'birthday', title: '生日'}
                , {field: 'registTime', title: '注册日期'}
                , {field: 'right', title: '操作', toolbar: '#barDemo'}
            ]]
        });

        // 事件注册
        table.on('tool(test)', function (obj) {
            var data = obj.data; //获得当前行数据
            //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var layEvent = obj.event;
            if (layEvent === 'del') { //删除
                layer.confirm('真的删除么', function (index) {
                    // 向服务端发送删除请求
                    // 此处可以发送ajax
                    $.ajax({
                        url: '${pageContext.request.contextPath}/users/' + data.id,
                        type: 'delete',
                        success: function (result) {
                            if (result.status) {
                                table.reload('demo', {});//重新加载数据
                            } else {
                                alert(result.message)
                            }
                            layer.close(index)
                        }

                    })
                    layer.close(index);
                });
            } else if (layEvent === 'edit') {
                location = "${pageContext.request.contextPath}/users/" + data.id

            }
        });

    })

</script>
</body>
</html>
